#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Word格式批量修改工具主程序
"""

import sys
import os
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                              QHBoxLayout, QLabel, QPushButton, QComboBox,
                              QSpinBox, QDoubleSpinBox, QFileDialog, QGroupBox,
                              QCheckBox, QTextEdit, QMessageBox, QLineEdit,
                              QTabWidget, QListWidget, QListWidgetItem,
                              QInputDialog, QDialog, QProgressDialog)
from PySide6.QtCore import Qt, QSize, QMimeData, QFileInfo
from PySide6.QtGui import QIcon, QDragEnterEvent, QDropEvent

import utils
from style_manager import StyleManager
from document_processor import DocumentProcessor
from utils.helpers import get_system_fonts
from utils.helpers import get_font_size_options
from utils.helpers import get_chinese_font_sizes

import platform

class WordFormatter(QMainWindow):
    def __init__(self):
        super().__init__()
        self.style_manager = StyleManager()
        self.document_processor = DocumentProcessor()
        self.current_file = None
        self.init_ui()
        self.load_default_templates()

    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("Word格式批量修改工具")
        self.setMinimumSize(800, 700)

        # 设置窗口图标
        if hasattr(sys, '_MEIPASS'):
            # 打包后的路径
            icon_path = os.path.join(sys._MEIPASS, 'resources', 'icons', 'app.ico')
        else:
            # 开发时的路径
            icon_path = os.path.join(os.path.dirname(__file__), 'resources', 'icons', 'app.ico')

        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))

        # 主窗口部件
        self.main_widget = QWidget()
        self.setCentralWidget(self.main_widget)

        # 主布局
        self.main_layout = QVBoxLayout()
        self.main_widget.setLayout(self.main_layout)

        # 创建标签页
        self.tab_widget = QTabWidget()
        self.main_layout.addWidget(self.tab_widget)

        # 添加格式修改标签页
        self.create_format_tab()

        # 添加模板管理标签页
        self.create_template_tab()

        # 添加状态栏
        self.status_bar = self.statusBar()
        self.status_bar.showMessage("就绪")

    def create_format_tab(self):
        """创建格式修改标签页"""
        self.format_tab = QWidget()
        self.tab_widget.addTab(self.format_tab, "格式修改")

        # 格式修改标签页布局
        self.format_layout = QVBoxLayout()
        self.format_tab.setLayout(self.format_layout)

        # 文件选择区域
        self.create_file_selection_group()

        # 样式选择区域
        self.create_style_selection_group()

        # 样式设置区域
        # self.create_style_settings_group()

        # 操作按钮区域
        self.create_action_buttons()

    def create_file_selection_group(self):
        """创建文件选择区域"""
        file_group = QGroupBox("文件选择")
        file_layout = QVBoxLayout()

        # 拖放区域
        self.drop_label = QLabel("拖放Word文件到这里或点击下方按钮选择文件")
        self.drop_label.setAlignment(Qt.AlignCenter)
        self.drop_label.setStyleSheet(
            "QLabel { border: 2px dashed #aaa; padding: 20px; }"
        )
        self.drop_label.setAcceptDrops(True)
        self.drop_label.dragEnterEvent = self.dragEnterEvent
        self.drop_label.dropEvent = self.dropEvent

        # 文件列表
        self.file_list = QListWidget()
        self.file_list.setSelectionMode(QListWidget.MultiSelection)

        # 按钮区域
        btn_layout = QHBoxLayout()
        self.select_file_btn = QPushButton("选择文件")
        self.select_file_btn.clicked.connect(self.select_files)
        self.clear_files_btn = QPushButton("清空列表")
        self.clear_files_btn.clicked.connect(self.clear_files)

        btn_layout.addWidget(self.select_file_btn)
        btn_layout.addWidget(self.clear_files_btn)

        file_layout.addWidget(self.drop_label)
        file_layout.addWidget(self.file_list)
        file_layout.addLayout(btn_layout)

        file_group.setLayout(file_layout)
        self.format_layout.addWidget(file_group)

    def create_style_selection_group(self):
        """创建样式选择区域"""
        style_group = QGroupBox("样式选择")
        style_layout = QVBoxLayout()

        # 模板选择
        template_layout = QHBoxLayout()
        template_layout.addWidget(QLabel("选择模板:"))

        self.template_combo = QComboBox()
        self.template_combo.addItems(self.style_manager.get_template_names())
        self.template_combo.currentTextChanged.connect(self.load_template_settings)
        template_layout.addWidget(self.template_combo)

        style_layout.addLayout(template_layout)

        # 样式类型选择
        type_layout = QHBoxLayout()
        type_layout.addWidget(QLabel("样式类型:"))

        self.style_type_combo = QComboBox()
        self.style_type_combo.addItems(["标题", "一级标题", "二级标题","三级标题","四级标题", "正文"])
        self.style_type_combo.currentTextChanged.connect(self.update_style_settings)
        type_layout.addWidget(self.style_type_combo)

        style_layout.addLayout(type_layout)

        style_group.setLayout(style_layout)
        self.format_layout.addWidget(style_group)

    def create_style_settings_group(self):
        """创建样式设置区域"""
        settings_group = QGroupBox("样式设置")
        self.settings_layout = QVBoxLayout()

        # 字体设置
        font_layout = QHBoxLayout()
        font_layout.addWidget(QLabel("字体:"))

        self.font_combo = QComboBox()
        self.font_combo.addItems(get_system_fonts())
        font_layout.addWidget(self.font_combo)

        font_layout.addWidget(QLabel("字号:"))
#        self.font_size = QSpinBox()
#        self.font_size.setRange(1, 72)
#        self.font_size.setValue(12)

        # 原代码替换
        # self.font_size = QSpinBox()
        # self.font_size.setRange(1, 72)
        # self.font_size.setValue(12)

        # 新代码
        self.font_size_combo = QComboBox()
        self.font_size_combo.addItems(get_font_size_options())
        self.font_size_combo.setCurrentText("小四")  # 默认小四号
        font_layout.addWidget(self.font_size_combo)

#        font_layout.addWidget(self.font_size)

        self.bold_check = QCheckBox("加粗")
        font_layout.addWidget(self.bold_check)

        self.italic_check = QCheckBox("斜体")
        font_layout.addWidget(self.italic_check)

        self.settings_layout.addLayout(font_layout)

        # 对齐方式
        align_layout = QHBoxLayout()
        align_layout.addWidget(QLabel("对齐方式:"))

        self.align_combo = QComboBox()
        self.align_combo.addItems(["左对齐", "居中", "右对齐", "两端对齐"])
        align_layout.addWidget(self.align_combo)

        self.settings_layout.addLayout(align_layout)

        # 段落设置
        para_layout = QHBoxLayout()
        para_layout.setContentsMargins(0, 0, 0, 0)
        para_layout.setSpacing(5)
        para_layout.setAlignment(Qt.AlignLeft)
        
        # 首行缩进组件
        label_spin_layout = QHBoxLayout()
        label_spin_layout.setContentsMargins(0, 0, 0, 0)
        label_spin_layout.setSpacing(5)
        label_spin_layout.addWidget(QLabel("首行缩进(磅):"))
        self.indent_spin = QDoubleSpinBox()
        self.indent_spin.setRange(0, 100)
        self.indent_spin.setSingleStep(0.5)
        self.indent_spin.setValue(28.9)
        label_spin_layout.addWidget(self.indent_spin)
        
        # 行间距组件
        line_spacing_layout = QHBoxLayout()
        line_spacing_layout.setContentsMargins(0, 0, 0, 0)
        line_spacing_layout.setSpacing(5)
        line_spacing_layout.addWidget(QLabel("行间距(倍):"))
        self.line_spacing = QDoubleSpinBox()
        self.line_spacing.setRange(0.5, 3)
        self.line_spacing.setSingleStep(0.1)
        self.line_spacing.setValue(1.5)
        line_spacing_layout.addWidget(self.line_spacing)
        
        para_layout.addLayout(label_spin_layout)
        para_layout.addLayout(line_spacing_layout)
        para_layout.addStretch(1)
        # self.indent_spin.setSingleStep(0.25)
        # self.indent_spin.setValue(0.35)
        # para_layout.addWidget(self.indent_spin)

        # para_layout.addWidget(QLabel("行间距(倍):"))
        # self.line_spacing = QDoubleSpinBox()
        # self.line_spacing.setRange(0.5, 3)
        # self.line_spacing.setSingleStep(0.1)
        # self.line_spacing.setValue(1.5)
        # para_layout.addWidget(self.line_spacing)
        self.settings_layout.addLayout(para_layout)

        # 段间距设置
        space_layout = QHBoxLayout()
        space_layout.addWidget(QLabel("段前间距(磅):"))

        self.space_before = QSpinBox()
        self.space_before.setRange(0, 48)
        self.space_before.setSingleStep(1)
        self.space_before.setValue(0)
        space_layout.addWidget(self.space_before)

        space_layout.addWidget(QLabel("段后间距(磅):"))
        self.space_after = QSpinBox()
        self.space_after.setRange(0, 48)
        self.space_after.setSingleStep(1)
        self.space_after.setValue(0)
        space_layout.addWidget(self.space_after)

        self.settings_layout.addLayout(space_layout)

        # 颜色设置
        color_layout = QHBoxLayout()
        color_layout.addWidget(QLabel("字体颜色:"))

        self.color_combo = QComboBox()
        self.color_combo.addItems(["黑色", "红色", "蓝色", "绿色", "自定义"])
        color_layout.addWidget(self.color_combo)

        self.settings_layout.addLayout(color_layout)

        # 保存为默认按钮
        self.save_as_default_btn = QPushButton("保存当前设置为默认")
        self.save_as_default_btn.clicked.connect(self.save_current_as_default)
        self.settings_layout.addWidget(self.save_as_default_btn)

        settings_group.setLayout(self.settings_layout)
        self.format_layout.addWidget(settings_group)
        self.font_size_combo.currentTextChanged.connect(self.preview_font_size)

    def preview_font_size(self, size_text):
        """字号预览"""
        # 在实际应用中可以实现实时预览效果
        self.status_bar.showMessage(f"当前字号: {size_text}", 2000)

    def create_action_buttons(self):
        """创建操作按钮区域"""
        btn_layout = QHBoxLayout()

        # self.preview_btn = QPushButton("预览")
        # self.preview_btn.clicked.connect(self.preview_changes)
        # btn_layout.addWidget(self.preview_btn)

        self.apply_btn = QPushButton("应用格式")
        self.apply_btn.clicked.connect(self.apply_format)
        btn_layout.addWidget(self.apply_btn)

        self.save_as_btn = QPushButton("另存为...")
        self.save_as_btn.clicked.connect(self.save_as)
        btn_layout.addWidget(self.save_as_btn)

        self.format_layout.addLayout(btn_layout)

    def create_template_tab(self):
        """创建模板管理标签页"""
        self.template_tab = QWidget()
        self.tab_widget.addTab(self.template_tab, "模板管理")

        # 模板管理标签页布局
        self.template_layout = QVBoxLayout()
        self.template_tab.setLayout(self.template_layout)

        # 模板列表
        self.create_template_list_group()

        # 模板编辑区域
        self.create_template_edit_group()

        # 模板操作按钮
        self.create_template_action_buttons()

    def create_template_list_group(self):
        """创建模板列表区域"""
        list_group = QGroupBox("模板列表")
        list_layout = QVBoxLayout()

        self.template_list = QListWidget()
        self.template_list.addItems(self.style_manager.get_template_names())
        self.template_list.currentItemChanged.connect(self.load_template_for_edit)

        list_layout.addWidget(self.template_list)
        list_group.setLayout(list_layout)
        self.template_layout.addWidget(list_group)

    def create_template_edit_group(self):
        """创建模板编辑区域"""
        edit_group = QGroupBox("模板编辑")
        self.edit_layout = QVBoxLayout()

        # 模板名称
        name_layout = QHBoxLayout()
        name_layout.addWidget(QLabel("模板名称:"))

        self.template_name_edit = QLineEdit()
        name_layout.addWidget(self.template_name_edit)

        self.edit_layout.addLayout(name_layout)

        # 样式类型选择
        type_layout = QHBoxLayout()
        type_layout.addWidget(QLabel("编辑样式类型:"))

        self.edit_style_type_combo = QComboBox()
        self.edit_style_type_combo.addItems(["标题", "一级标题", "二级标题","三级标题","四级标题", "正文"])
        self.edit_style_type_combo.currentTextChanged.connect(self.update_template_edit_fields)
        type_layout.addWidget(self.edit_style_type_combo)

        self.edit_layout.addLayout(type_layout)

        # 样式编辑区域
        self.create_template_style_edit_group()

        edit_group.setLayout(self.edit_layout)
        self.template_layout.addWidget(edit_group)

    def create_template_style_edit_group(self):
        """创建模板样式编辑区域"""
        # 清除之前的控件
        for i in reversed(range(self.edit_layout.count())):
            widget = self.edit_layout.itemAt(i).widget()
            if widget and widget not in [
                self.template_name_edit.parent(),
                self.edit_style_type_combo.parent()
            ]:
                widget.deleteLater()

        # 字体设置
        edit_font_layout = QHBoxLayout()
        edit_font_layout.addWidget(QLabel("字体:"))

        self.edit_font_combo = QComboBox()
        self.edit_font_combo.addItems(get_system_fonts())
        edit_font_layout.addWidget(self.edit_font_combo)

        edit_font_layout.addWidget(QLabel("字号:"))
        # self.edit_font_size = QSpinBox()
        # self.edit_font_size.setRange(1, 72)
        # self.edit_font_size.setValue(12)
        # edit_font_layout.addWidget(self.edit_font_size)

        self.edit_font_size_combo = QComboBox()
        self.edit_font_size_combo.addItems(get_font_size_options())
        self.edit_font_size_combo.setCurrentText("小四")  # 默认小四号
        edit_font_layout.addWidget(self.edit_font_size_combo)

        self.edit_bold_check = QCheckBox("加粗")
        edit_font_layout.addWidget(self.edit_bold_check)

        self.edit_italic_check = QCheckBox("斜体")
        edit_font_layout.addWidget(self.edit_italic_check)

        self.edit_layout.addLayout(edit_font_layout)

        # 对齐方式
        edit_align_layout = QHBoxLayout()
        edit_align_layout.addWidget(QLabel("对齐方式:"))

        self.edit_align_combo = QComboBox()
        self.edit_align_combo.addItems(["左对齐", "居中", "右对齐", "两端对齐"])
        edit_align_layout.addWidget(self.edit_align_combo)

        self.edit_layout.addLayout(edit_align_layout)

        # 段落设置
        edit_para_layout = QHBoxLayout()
        edit_para_layout.addWidget(QLabel("首行缩进(厘米):"))

        self.edit_indent_spin = QDoubleSpinBox()
        self.edit_indent_spin.setRange(0, 5)
        self.edit_indent_spin.setSingleStep(0.25)
        self.edit_indent_spin.setValue(0.35)
        edit_para_layout.addWidget(self.edit_indent_spin)

        edit_para_layout.addWidget(QLabel("行间距(倍):"))
        self.edit_line_spacing = QDoubleSpinBox()
        self.edit_line_spacing.setRange(0.5, 3)
        self.edit_line_spacing.setSingleStep(0.1)
        self.edit_line_spacing.setValue(1.5)
        edit_para_layout.addWidget(self.edit_line_spacing)

        self.edit_layout.addLayout(edit_para_layout)

        # 段间距设置
        edit_space_layout = QHBoxLayout()
        edit_space_layout.addWidget(QLabel("段前间距(磅):"))

        self.edit_space_before = QSpinBox()
        self.edit_space_before.setRange(0, 48)
        self.edit_space_before.setSingleStep(1)
        self.edit_space_before.setValue(0)
        edit_space_layout.addWidget(self.edit_space_before)

        edit_space_layout.addWidget(QLabel("段后间距(磅):"))
        self.edit_space_after = QSpinBox()
        self.edit_space_after.setRange(0, 48)
        self.edit_space_after.setSingleStep(1)
        self.edit_space_after.setValue(0)
        edit_space_layout.addWidget(self.edit_space_after)

        self.edit_layout.addLayout(edit_space_layout)

        # 颜色设置
        edit_color_layout = QHBoxLayout()
        edit_color_layout.addWidget(QLabel("字体颜色:"))

        self.edit_color_combo = QComboBox()
        self.edit_color_combo.addItems(["黑色", "红色", "蓝色", "绿色", "自定义"])
        edit_color_layout.addWidget(self.edit_color_combo)

        self.edit_layout.addLayout(edit_color_layout)

    def create_template_action_buttons(self):
        """创建模板操作按钮"""
        btn_layout = QHBoxLayout()

        self.new_template_btn = QPushButton("新建模板")
        self.new_template_btn.clicked.connect(self.new_template)
        btn_layout.addWidget(self.new_template_btn)

        self.save_template_btn = QPushButton("保存模板")
        self.save_template_btn.clicked.connect(self.save_template)
        btn_layout.addWidget(self.save_template_btn)

        self.delete_template_btn = QPushButton("删除模板")
        self.delete_template_btn.clicked.connect(self.delete_template)
        btn_layout.addWidget(self.delete_template_btn)

        self.set_default_template_btn = QPushButton("设为默认模板")
        self.set_default_template_btn.clicked.connect(self.set_default_template)
        btn_layout.addWidget(self.set_default_template_btn)

        self.template_layout.addLayout(btn_layout)

    def load_default_templates(self):
        """加载默认模板"""
        # 这里可以添加从文件加载默认模板的逻辑
        pass

    def dragEnterEvent(self, event: QDragEnterEvent):
        """拖拽进入事件处理"""
        if event.mimeData().hasUrls():
            event.acceptProposedAction()

    def dropEvent(self, event: QDropEvent):
        """拖放事件处理"""
        for url in event.mimeData().urls():
            file_path = url.toLocalFile()
            if file_path.lower().endswith(('.doc', '.docx')):
                self.add_file_to_list(file_path)

    def select_files(self):
        """选择文件"""
        files, _ = QFileDialog.getOpenFileNames(
            self, "选择Word文件", "",
            "Word文件 (*.doc *.docx);;所有文件 (*.*)"
        )
        for file in files:
            self.add_file_to_list(file)

    def add_file_to_list(self, file_path):
        """添加文件到列表"""
        if not os.path.exists(file_path):
            return

        # 检查是否已存在
        for i in range(self.file_list.count()):
            if self.file_list.item(i).data(Qt.UserRole) == file_path:
                return

        item = QListWidgetItem(QFileInfo(file_path).fileName())
        item.setData(Qt.UserRole, file_path)
        self.file_list.addItem(item)

    def clear_files(self):
        """清空文件列表"""
        self.file_list.clear()

    def load_template_settings(self, template_name):
        """加载模板设置"""
        # 这里实现从模板加载设置到UI
        template = self.style_manager.get_template(template_name)
        if not template:
            return

        # 更新当前样式类型的设置
        # self.update_style_settings()

    def update_style_settings(self):
        """更新样式设置到UI"""
        style_type = self.style_type_combo.currentText()
        template_name = self.template_combo.currentText()

        if not template_name or not style_type:
            return

        # 获取当前模板的样式设置
        template = self.style_manager.get_template(template_name)
        if not template:
            return

        # 映射样式类型到模板键
        style_map = {
            "标题": "title",
            "一级标题": "heading1",
            "二级标题": "heading2",
            "三级标题": "heading3",
            "四级标题": "heading4",
            "正文": "body"
        }

        style_key = style_map.get(style_type)
        if not style_key or style_key not in template:
            return

        style = template[style_key]

        # 更新UI控件
        # self.font_combo.setCurrentText(style.get("font", "宋体"))
        # self.font_size_combo.setCurrentText(str(style.get("size", 12)))
        # self.edit_font_size.setValue(style.get("size", 12))
        # self.bold_check.setChecked(style.get("bold", False))
        # self.italic_check.setChecked(style.get("italic", False))

        # 对齐方式
        align_map = {
            "left": 0,
            "center": 1,
            "right": 2,
            "justify": 3
        }
        alignment = style.get("alignment", "left")
        self.align_combo.setCurrentIndex(align_map.get(alignment, 0))

        # 段落设置
        self.indent_spin.setValue(style.get("first_line_indent", 0.35))
        self.line_spacing.setValue(style.get("line_spacing", 1.5))

        # 段间距
        self.space_before.setValue(style.get("space_before", 0))
        self.space_after.setValue(style.get("space_after", 0))

        # 颜色设置
        color = style.get("color", "黑色")
        if color in ["黑色", "红色", "蓝色", "绿色"]:
            self.color_combo.setCurrentText(color)
        else:
            self.color_combo.setCurrentText("自定义")

    def save_current_as_default(self):
        """保存当前设置为默认"""
        style_type = self.style_type_combo.currentText()
        template_name = self.template_combo.currentText()

        if not template_name or not style_type:
            QMessageBox.warning(self, "警告", "请选择模板和样式类型")
            return

        # 获取当前UI设置
        style = self.get_current_style_settings()

        # 映射样式类型到模板键
        style_map = {
            "标题": "title",
            "一级标题": "heading1",
            "二级标题": "heading2",
            "三级标题": "heading3",
            "四级标题": "heading4",
            "正文": "body"
        }

        style_key = style_map.get(style_type)
        if not style_key:
            return

        # 更新模板
        self.style_manager.update_template_style(template_name, style_key, style)
        QMessageBox.information(self, "成功", "已保存当前设置为默认")

    def get_current_style_settings(self):
        """获取当前UI中的样式设置"""
        style = {
            "font": self.font_combo.currentText(),
            "size": self.font_size_combo.currentText(),
            "bold": self.bold_check.isChecked(),
            "italic": self.italic_check.isChecked(),
            "alignment": ["left", "center", "right", "justify"][self.align_combo.currentIndex()],
            "first_line_indent": self.indent_spin.value(),
            "line_spacing": self.line_spacing.value(),
            "space_before": self.space_before.value(),
            "space_after": self.space_after.value(),
            "color": self.color_combo.currentText() if self.color_combo.currentText() != "自定义" else "黑色"
        }
        return style

    def preview_changes(self):
        """预览更改"""
        if self.file_list.count() == 0:
            QMessageBox.warning(self, "警告", "请先添加文件")
            return

        selected_items = self.file_list.selectedItems()
        if not selected_items:
            QMessageBox.warning(self, "警告", "请选择要预览的文件")
            return

        file_path = selected_items[0].data(Qt.UserRole)
        template_name = self.template_combo.currentText()

        if not template_name:
            QMessageBox.warning(self, "警告", "请选择模板")
            return

        # 获取模板
        template = self.style_manager.get_template(template_name)
        if not template:
            QMessageBox.warning(self, "警告", "模板不存在")
            return

        # 创建预览窗口
        preview_dialog = QDialog(self)
        preview_dialog.setWindowTitle("格式预览 - " + os.path.basename(file_path))
        preview_dialog.resize(600, 800)

        layout = QVBoxLayout()
        preview_text = QTextEdit()
        preview_text.setReadOnly(True)

        try:
            # 应用格式并获取预览文本
            preview_content = self.document_processor.preview_format(file_path, template)
            preview_text.setHtml(preview_content)
        except Exception as e:
            preview_text.setPlainText(f"预览失败: {str(e)}")

        layout.addWidget(preview_text)

        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(preview_dialog.close)
        layout.addWidget(close_btn)

        preview_dialog.setLayout(layout)
        preview_dialog.exec_()

    def apply_format(self):
        """应用格式"""
        if self.file_list.count() == 0:
            QMessageBox.warning(self, "警告", "请先添加文件")
            return

        template_name = self.template_combo.currentText()
        if not template_name:
            QMessageBox.warning(self, "警告", "请选择模板")
            return

        # 获取模板
        template = self.style_manager.get_template(template_name)
        if not template:
            QMessageBox.warning(self, "警告", "模板不存在")
            return

        # 处理所有文件
        success_count = 0
        total_count = self.file_list.count()

        progress_dialog = QProgressDialog("正在应用格式...", "取消", 0, total_count, self)
        progress_dialog.setWindowTitle("处理中")
        progress_dialog.setWindowModality(Qt.WindowModal)
        progress_dialog.setAutoClose(True)

        for i in range(total_count):
            progress_dialog.setValue(i)
            if progress_dialog.wasCanceled():
                break

            item = self.file_list.item(i)
            file_path = item.data(Qt.UserRole)

            try:
                self.document_processor.apply_format(file_path, template)
                success_count += 1
            except Exception as e:
                QMessageBox.warning(self, "错误", f"处理文件 {os.path.basename(file_path)} 失败: {str(e)}")

        progress_dialog.setValue(total_count)
        QMessageBox.information(self, "完成", f"成功处理 {success_count}/{total_count} 个文件")

    def save_as(self):
        """另存为"""
        if self.file_list.count() == 0:
            QMessageBox.warning(self, "警告", "请先添加文件")
            return

        selected_items = self.file_list.selectedItems()
        if not selected_items:
            QMessageBox.warning(self, "警告", "请选择要另存的文件")
            return

        file_path = selected_items[0].data(Qt.UserRole)
        template_name = self.template_combo.currentText()

        if not template_name:
            QMessageBox.warning(self, "警告", "请选择模板")
            return

        # 获取模板
        template = self.style_manager.get_template(template_name)
        if not template:
            QMessageBox.warning(self, "警告", "模板不存在")
            return

        # 选择保存路径
        save_path, _ = QFileDialog.getSaveFileName(
            self, "另存为",
            os.path.splitext(file_path)[0] + "_formatted.docx",
            "Word文档 (*.docx);;所有文件 (*.*)"
        )

        if not save_path:
            return

        try:
            self.document_processor.apply_format(file_path, template, save_path)
            QMessageBox.information(self, "成功", "文件已保存")
        except Exception as e:
            QMessageBox.warning(self, "错误", f"保存文件失败: {str(e)}")

    def new_template(self):
        """新建模板"""
        name, ok = QInputDialog.getText(
            self, "新建模板", "输入模板名称:",
            QLineEdit.Normal, "新模板"
        )

        if ok and name:
            if name in self.style_manager.get_template_names():
                qmessagebox.warning(self, "警告", "模板已存在")
                return

               # 创建新模板
            self.style_manager.add_template(name, {
                "title": {
                    "font": "黑体", "size": 16, "bold": True,
                    "alignment": "center", "space_after": 12,
                    "color": "黑色"
                },
                "heading1": {
                    "font": "黑体", "size": 14, "bold": True,
                    "alignment": "left", "space_before": 12,
                    "space_after": 6, "color": "黑色"
                },
                "heading2": {
                    "font": "楷体", "size": 12, "bold": True,
                    "alignment": "left", "space_before": 6,
                    "space_after": 6, "color": "黑色"
                   },
                "body": {
                    "font": "宋体", "size": 12, "bold": False,
                    "alignment": "left", "first_line_indent": 0.35,
                    "line_spacing": 1.5, "color": "黑色"
                 }
            })

               # 更新ui
        self.template_combo.addItem(name)
        self.template_list.addItem(name)
        self.template_combo.setCurrentText(name)

    def load_template_for_edit(self, current: QListWidgetItem, previous: QListWidgetItem):
        """加载模板到编辑区域"""
        if not current:
            return

        template_name = current.text()
        self.template_name_edit.setText(template_name)
        self.update_template_edit_fields()

    def update_template_edit_fields(self):
        """更新模板编辑字段"""
        template_name = self.template_name_edit.text()
        style_type = self.edit_style_type_combo.currentText()

        if not template_name or not style_type:
            return

        # 获取模板
        template = self.style_manager.get_template(template_name)
        if not template:
            return

        # 映射样式类型到模板键
        style_map = {
            "标题": "title",
            "一级标题": "heading1",
            "二级标题": "heading2",
            "三级标题": "heading3",
            "四级标题": "heading4",
            "正文": "body"
        }

        style_key = style_map.get(style_type)
        if not style_key or style_key not in template:
            return

        style = template[style_key]

        # 更新编辑控件
        self.edit_font_combo.setCurrentText(style.get("font", "宋体"))
        self.edit_font_size_combo.setCurrentText(str(style.get("size", 12)))

        self.edit_bold_check.setChecked(style.get("bold", False))
        self.edit_italic_check.setChecked(style.get("italic", False))

        # 对齐方式
        align_map = {
            "left": 0,
            "center": 1,
            "right": 2,
            "justify": 3
        }
        alignment = style.get("alignment", "left")
        self.edit_align_combo.setCurrentIndex(align_map.get(alignment, 0))

        # 段落设置
        self.edit_indent_spin.setValue(style.get("first_line_indent", 0.35))
        self.edit_line_spacing.setValue(style.get("line_spacing", 1.5))

        # 段间距
        self.edit_space_before.setValue(style.get("space_before", 0))
        self.edit_space_after.setValue(style.get("space_after", 0))

        # 颜色设置
        color = style.get("color", "黑色")
        if color in ["黑色", "红色", "蓝色", "绿色"]:
            self.edit_color_combo.setCurrentText(color)
        else:
            self.edit_color_combo.setCurrentText("自定义")

    def save_template(self):
        """保存模板"""
        old_name = self.template_list.currentItem().text()
        new_name = self.template_name_edit.text()

        if not new_name:
            QMessageBox.warning(self, "警告", "模板名称不能为空")
            return

        # 获取当前编辑的样式设置
        style_type = self.edit_style_type_combo.currentText()
        style_map = {
            "标题": "title",
            "一级标题": "heading1",
            "二级标题": "heading2",
            "三级标题": "heading3",
            "四级标题": "heading4",
            "正文": "body"
        }
        style_key = style_map.get(style_type)

        if not style_key:
            return

        style = {
            "font": self.edit_font_combo.currentText(),
            "size": self.edit_font_size_combo.currentText(),
            "bold": self.edit_bold_check.isChecked(),
            "italic": self.edit_italic_check.isChecked(),
            "alignment": ["left", "center", "right", "justify"][self.edit_align_combo.currentIndex()],
            "first_line_indent": self.edit_indent_spin.value(),
            "line_spacing": self.edit_line_spacing.value(),
            "space_before": self.edit_space_before.value(),
            "space_after": self.edit_space_after.value(),
            "color": self.edit_color_combo.currentText() if self.edit_color_combo.currentText() != "自定义" else "黑色"
        }

        # 如果是重命名
        if old_name != new_name:
            if new_name in self.style_manager.get_template_names():
                QMessageBox.warning(self, "警告", "模板名称已存在")
                return

            self.style_manager.rename_template(old_name, new_name)

            # 更新UI
            self.template_list.currentItem().setText(new_name)

            # 更新模板选择下拉框
            index = self.template_combo.findText(old_name)
            if index >= 0:
                self.template_combo.setItemText(index, new_name)

        # 更新模板样式
        self.style_manager.update_template_style(new_name, style_key, style)
        QMessageBox.information(self, "成功", "模板已保存")

    def delete_template(self):
        """删除模板"""
        current_item = self.template_list.currentItem()
        if not current_item:
            return

        template_name = current_item.text()

        reply = QMessageBox.question(
            self, "确认删除",
            f"确定要删除模板 '{template_name}' 吗?",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            # 从管理器删除
            self.style_manager.remove_template(template_name)

            # 从列表删除
            row = self.template_list.row(current_item)
            self.template_list.takeItem(row)

            # 从下拉框删除
            index = self.template_combo.findText(template_name)
            if index >= 0:
                self.template_combo.removeItem(index)

    def set_default_template(self):
        """设为默认模板"""
        current_item = self.template_list.currentItem()
        if not current_item:
            return

        template_name = current_item.text()
        self.style_manager.set_default_template(template_name)
        QMessageBox.information(self, "成功", f"已设置 '{template_name}' 为默认模板")

if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 设置应用程序样式
    if platform.system() == "Darwin":  # macOS
        app.setStyle("Fusion")

    window = WordFormatter()
    window.show()
    sys.exit(app.exec())
